
let currentArticles = [];
let selectedArticleId = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadArticles();
    updateStats();
});

// 加载文章列表
async function loadArticles(status = '') {
    const container = document.getElementById('articlesContainer');
    const spinner = document.getElementById('loadingSpinner');
    
    spinner.style.display = 'block';
    container.innerHTML = '';
    
    try {
        const url = status ? `/api/articles?status=${status}` : '/api/articles';
        const response = await fetch(url);
        currentArticles = await response.json();
        
        spinner.style.display = 'none';
        
        if (currentArticles.length === 0) {
            container.innerHTML = `
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-inbox"></i>
                        <h5>暂无文章</h5>
                        <p>点击"生成今日文章"按钮开始创建内容</p>
                    </div>
                </div>
            `;
            return;
        }
        
        renderArticles(currentArticles);
    } catch (error) {
        console.error('加载文章失败:', error);
        spinner.style.display = 'none';
        container.innerHTML = `
            <div class="col-12">
                <div class="alert alert-danger">
                    加载文章失败，请稍后重试
                </div>
            </div>
        `;
    }
}

// 渲染文章列表
function renderArticles(articles) {
    const container = document.getElementById('articlesContainer');
    container.innerHTML = '';
    
    articles.forEach(article => {
        const card = createArticleCard(article);
        container.appendChild(card);
    });
}

// 创建文章卡片
function createArticleCard(article) {
    const col = document.createElement('div');
    col.className = 'col-md-4 col-sm-6';
    
    const statusClass = {
        'draft': 'bg-warning',
        'published': 'bg-success',
        'rejected': 'bg-danger'
    };
    
    const statusText = {
        'draft': '草稿',
        'published': '已发布',
        'rejected': '已拒绝'
    };
    
    col.innerHTML = `
        <div class="card article-card">
            <div class="position-relative">
                <img src="${article.cover_image || 'https://via.placeholder.com/400x200?text=No+Image'}" 
                     class="card-img-top article-image" alt="${article.title}">
                <span class="badge ${statusClass[article.status] || 'bg-secondary'} status-badge">
                    ${statusText[article.status] || '未知'}
                </span>
            </div>
            <div class="card-body">
                <h6 class="card-title">${article.title}</h6>
                <p class="card-text text-muted small">${article.summary || article.content.substring(0, 100) + '...'}</p>
                
                <div class="article-meta mb-2">
                    <i class="far fa-clock"></i> ${formatDate(article.created_at)}
                </div>
                
                <div class="mb-2">
                    ${article.tags ? article.tags.map(tag => `<span class="tag">${tag}</span>`).join('') : ''}
                </div>
                
                <div class="btn-group btn-group-sm w-100">
                    <button class="btn btn-outline-primary" onclick="viewArticle(${article.id})">
                        <i class="fas fa-eye"></i> 查看
                    </button>
                    <button class="btn btn-outline-success" onclick="publishArticle(${article.id})" ${article.status === 'published' ? 'disabled' : ''}>
                        <i class="fas fa-paper-plane"></i> 发布
                    </button>
                    <button class="btn btn-outline-danger" onclick="deleteArticle(${article.id})">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </div>
            </div>
        </div>
    `;
    
    return col;
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 生成文章
async function generateArticles() {
    const button = event.target;
    button.disabled = true;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 生成中...';
    
    try {
        const response = await fetch('/api/articles/generate', {
            method: 'POST'
        });
        const result = await response.json();
        
        alert(result.message);
        loadArticles();
        updateStats();
    } catch (error) {
        console.error('生成文章失败:', error);
        alert('生成文章失败，请稍后重试');
    } finally {
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-magic"></i> 生成今日文章';
    }
}

// 刷新文章列表
function refreshArticles() {
    const status = document.getElementById('statusFilter').value;
    loadArticles(status);
}

// 筛选文章
function filterArticles() {
    const status = document.getElementById('statusFilter').value;
    loadArticles(status);
}

// 查看文章详情
async function viewArticle(articleId) {
    try {
        const response = await fetch(`/api/articles/${articleId}`);
        const article = await response.json();
        
        selectedArticleId = articleId;
        
        document.getElementById('articleDetails').innerHTML = `
            <h4>${article.title}</h4>
            <p class="text-muted">创建时间: ${formatDate(article.created_at)}</p>
            
            ${article.cover_image ? `<img src="${article.cover_image}" class="img-fluid mb-3" alt="${article.title}">` : ''}
            
            <div class="mb-3">
                <strong>标签:</strong>
                ${article.tags ? article.tags.map(tag => `<span class="tag">${tag}</span>`).join('') : '无'}
            </div>
            
            <div class="mb-3">
                <strong>摘要:</strong>
                <p>${article.summary || '无摘要'}</p>
            </div>
            
            <div class="mb-3">
                <strong>内容:</strong>
                <div class="border p-3 bg-light">
                    ${article.content.replace(/\n/g, '<br>')}
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-3">
                    <strong>状态:</strong>
                    <span class="badge ${article.status === 'published' ? 'bg-success' : article.status === 'draft' ? 'bg-warning' : 'bg-danger'}">
                        ${article.status === 'published' ? '已发布' : article.status === 'draft' ? '草稿' : '已拒绝'}
                    </span>
                </div>
                <div class="col-md-3">
                    <strong>阅读量:</strong> ${article.view_count || 0}
                </div>
                <div class="col-md-3">
                    <strong>点赞:</strong> ${article.like_count || 0}
                </div>
                <div class="col-md-3">
                    <strong>分享:</strong> ${article.share_count || 0}
                </div>
            </div>
        `;
        
        document.getElementById('publishBtn').style.display = article.status === 'published' ? 'none' : 'inline-block';
        
        const modal = new bootstrap.Modal(document.getElementById('articleModal'));
        modal.show();
    } catch (error) {
        console.error('获取文章详情失败:', error);
        alert('获取文章详情失败');
    }
}

// 发布文章
async function publishArticle(articleId = null) {
    const id = articleId || selectedArticleId;
    if (!id) return;
    
    if (!confirm('确定要发布这篇文章吗？')) return;
    
    try {
        const response = await fetch(`/api/articles/${id}/publish`, {
            method: 'POST'
        });
        
        if (response.ok) {
            alert('文章发布成功');
            const modal = bootstrap.Modal.getInstance(document.getElementById('articleModal'));
            if (modal) modal.hide();
            loadArticles();
            updateStats();
        }
    } catch (error) {
        console.error('发布文章失败:', error);
        alert('发布文章失败');
    }
}

// 删除文章
async function deleteArticle(articleId) {
    if (!confirm('确定要删除这篇文章吗？此操作不可恢复！')) return;
    
    try {
        const response = await fetch(`/api/articles/${articleId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            alert('文章删除成功');
            loadArticles();
            updateStats();
        }
    } catch (error) {
        console.error('删除文章失败:', error);
        alert('删除文章失败');
    }
}

// 更新统计信息
async function updateStats() {
    try {
        const response = await fetch('/api/articles');
        const articles = await response.json();
        
        const total = articles.length;
        const draft = articles.filter(a => a.status === 'draft').length;
        const published = articles.filter(a => a.status === 'published').length;
        
        const today = new Date().toDateString();
        const todayArticles = articles.filter(a => new Date(a.created_at).toDateString() === today).length;
        
        document.getElementById('totalCount').textContent = total;
        document.getElementById('draftCount').textContent = draft;
        document.getElementById('publishedCount').textContent = published;
        document.getElementById('todayCount').textContent = todayArticles;
    } catch (error) {
        console.error('更新统计失败:', error);
    }
}
